package bm.com.framework.common.unit;

import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.Objects;

@Component
public class SpringContextUtils implements BeanFactoryPostProcessor, ApplicationContextAware {

    /** Spring应用上下文环境 */
    private static ConfigurableListableBeanFactory beanFactory;

    /**
     * 获取上下文对象
     */
    private static ApplicationContext applicationContext;

    /**
     * 构造函数获取类
     * @param applicationContext
     * @throws BeansException
     */
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringContextUtils.applicationContext = applicationContext;
    }

    /**
     * 通过类型获取Bean
     * @param requiredType
     * @return
     * @param <T>
     */
    public static <T> T getBean(Class<T> requiredType){
        return applicationContext.getBean(requiredType);
    }

    /** 获取上下问信息 */
    public static ApplicationContext getApplicationContext(){
        return applicationContext;
    }

    /**
     *  获取http请求头信息
     * @return
     */
    public static HttpServletRequest getHttpServletRequest(){
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
        return Objects.isNull(requestAttributes)?null:requestAttributes.getRequest();
    }

    /**
     * 获取请求头信息
     * @return
     */
    public static String  getToken(){
        HttpServletRequest getHttpServletRequest= getHttpServletRequest();
        return getHttpServletRequest.getHeader("token");
    }

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory configurableListableBeanFactory) throws BeansException {
        SpringContextUtils.beanFactory = beanFactory;
    }
}
